package com.wonders.frame.chron.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wonders.frame.console.controller.AbstractGenericRelationObjController;
import com.wonders.frame.console.model.bo.User;
import com.wonders.frame.console.model.vo.LoginInfo;
import com.wonders.frame.console.model.vo.TokenInfo;
import com.wonders.frame.console.service.TokenService;
import com.wonders.frame.console.service.UserService;
import com.wonders.frame.core.model.vo.ReturnObj;

@Controller
@RequestMapping("/api/login")
public class LoginController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private UserService userService;
	
	@Resource
	private TokenService tokenService;
	
	
	@RequestMapping(value = "/{ruleTypeId}", method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public ReturnObj<LoginInfo> login(
			@PathVariable("ruleTypeId") Integer ruleTypeId,
			@RequestParam(value = "loginName", required = true) String loginName,
			@RequestParam(value = "password", required = true) String pwd,
			@RequestParam(value = "maxAge", required = false,defaultValue = "0") long maxAge,
			HttpServletRequest request,HttpServletResponse response) {
		logger.debug("userLogin {}",ruleTypeId);
		
		ReturnObj<LoginInfo> rs=userService.loginWithEncodePwd(loginName, pwd, ruleTypeId);
		if(rs.getInfo().getSuccess()){
			//maxAge=0时，默认只记录sessionToken，不生成长效token,times>0时，限制使用次数
			tokenService.generateTokenAndSave(request,response,rs.getData(), maxAge,-1);
		}
		
		return rs;
		
	}
}
